package com.atguigu.gmall.order.mq;


import com.atguigu.gmall.common.util.JsonUtils;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.fasterxml.jackson.core.type.TypeReference;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Slf4j
@Component
public class OrderDeduceStockStatusListener {


    @Autowired
    OrderInfoService orderInfoService;
    /**
     * 监听减库存成功队列结果
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                    value =@Queue(value = "queue.ware.order", durable = "true", autoDelete = "false", exclusive = "false"),
                    exchange = @Exchange(value = "exchange.direct.ware.order",durable = "true", autoDelete = "false"),
                    key = "ware.order"
            )
    })
    public void listenOrderDeduceStockStatus(Channel channel, Message message) {
        //{orderId=43279847239，status='DEDUCTED、OUT_OF_STOCK'}
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try{
            Map<String, String> map = JsonUtils.converMessageToObject(message, new TypeReference<Map<String, String>>() {
            });
            String orderId = map.get("orderId");
            String status = map.get("status");
            //1、查出订单
            OrderInfo info = orderInfoService.getById(Long.parseLong(orderId));

            //2、修改订单状态
            OrderStatus orderStatus = null;
            ProcessStatus processStatus = null;
            if("DEDUCTED".equals(status)){
                //减库存成功
                orderStatus =OrderStatus.WAITING_DELEVER;
                processStatus = ProcessStatus.WAITING_DELEVER;

            }else {
                //减库存失败。库存超卖了
                orderStatus = OrderStatus.WAITING_DH;
                processStatus = ProcessStatus.WATING_DH;
            }


            //修改订单状态
            orderInfoService.updateOrderStatusById(info.getId(),info.getUserId(),orderStatus.name(),processStatus.name());


            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            try {
                channel.basicReject(deliveryTag,true);
            } catch (IOException ex) {
                log.error("消息队列异常:{}",e);
            }
        }
    }
}
